<script setup>
import {ref ,defineProps,computed,onMounted,watch} from 'vue'
import ResumeBubble from "@/views/messageBox/components/ResumeBubble.vue";
import {userUserStore} from "@/stores/index.js";
import {messageStore} from "@/stores/modules/messageStore.js";
import {getStuInfo} from "@/api/stu.js";
import {getCompanyInfo} from "@/api/company.js";

const props = defineProps({
  message: {
    type: Object, // 消息可以是字符串（文本）或对象（文件）
    required: true,
  },
  userInfo: Object,
  jobInfo: Object,
  prevTime: String,
})

const nowRole = ref(messageStore().nowRole)
const messageJson = ref('')

// 计算属性，判断 message是否以 "pdf" 结尾
const isPdf = computed(() => {
  try {
    // 尝试解析 content 为 JSON
    const contentParsed = JSON.parse(props.message.content);

    // 如果解析成功，并且是一个有效的 JSON 格式
    if (contentParsed && typeof contentParsed === 'object') {
      // 检查是否以 ".pdf" 结尾
      if (contentParsed?.filePath.toLowerCase().endsWith('.pdf')) {
        messageJson.value = contentParsed; // 保存 pdf 文件路径
        return true;
      }
      return false;
    }
  } catch (e) {
  }
  return false;
})

const formatMessageTime = (time) => {
  const sentTime = new Date(time);
  if (isNaN(sentTime)) return "时间格式错误";

  const now = new Date();
  const diffInMillis = now - sentTime;
  const diffInDays = Math.floor(diffInMillis / (1000 * 60 * 60 * 24));

  if (diffInDays > 1) {
    return sentTime.toISOString().split('T')[0];
  } else {
    const hours = sentTime.getHours().toString().padStart(2, '0');
    const minutes = sentTime.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  }
}

const messageTime = computed(() => {
  return formatMessageTime(props.message.sentTime)
});

// 计算属性，判断 messageTime 是否和上一条消息的时间相同
const showMessageTime = computed(() => {
  const currentTime = formatMessageTime(props.message.sentTime);
  const prevTime = props.prevTime ? formatMessageTime(props.prevTime) : null;

  if (prevTime) {
    // 如果当前是时间（小时:分钟），则比较时间是否相同
    if (currentTime.includes(':') && prevTime.includes(':')) {
      const [currentHour, currentMinute] = currentTime.split(':');
      const [prevHour, prevMinute] = prevTime.split(':');
      if (currentHour === prevHour && currentMinute === prevMinute) {
        return false; // 时间相同，不显示
      }
    }
    // 如果当前是日期（YYYY-MM-DD），则比较日期是否相同
    else if (currentTime === prevTime) {
      return false; // 日期相同，不显示
    }
  }
  return true; // 如果时间或日期不同，显示时间/日期
});

// 计算属性，将 \n 转换成 <br>
const formattedContent = computed(() => {
  if (props.message.content) {
    return props.message.content.replace(/\n/g, '<br>');
  }
  return '';
});
</script>

<template>
  <!-- 显示消息时间 -->
  <a-space class="message-time" v-if="showMessageTime">
    {{ messageTime }}
  </a-space>
  <div :class="['chat-bubble', nowRole === message.senderRole ? 'student' : 'company']">
    <div class="avatar-container">
      <a-avatar v-if="message.senderRole==='company'&&nowRole==='student'" :size="45" :src="userInfo?.logo"/>
      <a-avatar v-if="message.senderRole==='student'&&nowRole==='company'" :size="45" :src="userInfo?.profilePicturePath"/>
    </div>
    <div :class="['message', isPdf ? 'pdf' : '']">
      <!-- 如果 messageInput 是对象，则显示文件预览 -->
      <template v-if="isPdf">
        <ResumeBubble :file="messageJson" />
      </template>
      <!-- 如果 messageInput 是字符串，则显示文本 -->
      <div v-html="formattedContent" v-if="!isPdf" />
    </div>
    <div class="avatar-container">
      <a-avatar v-if="message.senderRole==='company'&&nowRole==='company'" :size="45" :src="userInfo?.logo"/>
      <a-avatar v-if="message.senderRole==='student'&&nowRole==='student'" :size="45" :src="userInfo?.profilePicturePath"/>
    </div>
  </div>
</template>

<style scoped>
.chat-bubble {
  display: flex;
  align-items: center;
  margin: 0 0 20px 0;
}
.chat-bubble.company {
  justify-content: flex-start; /* 招聘者在左侧 */
}
.chat-bubble.student {
  justify-content: flex-end; /* 求职者在右侧 */
}

.avatar-container {
  display: flex;
  align-items: center;
  margin: 0 5px;
}

.message {
  max-width: 70%;
  padding: 10px;
  border-radius: 10px;
  background-color: #f1f1f1;
  color: #333;
  font-size: 14px;
  position: relative;
  margin:0 8px;
}

.pdf {
  background-color: #e6f7ff !important;
  padding: 5px 10px !important;
}

.chat-bubble.company .message {
  background-color: #f8f8f8;
}
.chat-bubble.student .message {
  background-color: #c8e6c9;
}

.message-time {
  width: 100%;
  height: 15px;
  text-align: center;
  display: flex;
  justify-content: center;
  font-size: 12px;
  color: #1e1f22;
  margin: 5px 0;
  top: -15px;
}
</style>
